package manager

import (
	"context"
	"fmt"

	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

func GetKubeClientInCluster() (*kubernetes.Clientset, *rest.Config, error) {
	config, err := rest.InClusterConfig()
	if err != nil {
		return nil, nil, err
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		return nil, nil, err
	}
	return clientset, config, nil
}

// CreateNamespace 创建namespace
func CreateNamespace(kubeClient *kubernetes.Clientset, ctx context.Context, ns string) error {
	nsClient := kubeClient.CoreV1().Namespaces()
	namespace := &corev1.Namespace{
		TypeMeta: metav1.TypeMeta{
			Kind:       "Namespace",
			APIVersion: "v1",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      ns,
			Namespace: ns,
		},
	}
	_, err := nsClient.Create(ctx, namespace, metav1.CreateOptions{})
	if err != nil {
		return err
	}
	return nil
}

func GetNamespace(kubeClient *kubernetes.Clientset, ctx context.Context, name string) (ns *corev1.Namespace, e error) {
	nsClient := kubeClient.CoreV1().Namespaces()
	return nsClient.Get(ctx, name, metav1.GetOptions{})
}

func GetDeployment(
	kubeClient *kubernetes.Clientset,
	ctx context.Context,
	previewerId, 
	namespace string,
) (deployment *appsv1.Deployment, err error) {
	appClient := kubeClient.AppsV1().Deployments(namespace)
	return appClient.Get(ctx, previewerId, metav1.GetOptions{})
}

func DeleteDeployment(
	kubeClient *kubernetes.Clientset,
	ctx context.Context,
	previewerId,
	namespace string,
) (err error) {
	appClient := kubeClient.AppsV1().Deployments(namespace)
	return appClient.Delete(ctx, previewerId, metav1.DeleteOptions{})
}

// CreateDeployment
func CreateDeployment(
	kubeClient *kubernetes.Clientset,
	ctx context.Context,
	previewerId,
	namespace,
	previewerImageName,
	sidecarImageName,
	imagePullSecret string,
	previewerContainerEnv,
	sidecarContainerEnv map[string]string,
	previewerContainerPort,
	sidecarContainerPort map[string]int32,
) (e error) {
	appClient := kubeClient.AppsV1().Deployments(namespace)
	dep := &appsv1.Deployment{
		TypeMeta: metav1.TypeMeta{
			Kind:       "Deployment",
			APIVersion: "apps/v1",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      previewerId,
			Namespace: namespace,
		},
		Spec: appsv1.DeploymentSpec{
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"previewer-id": previewerId,
				},
			},
			Replicas: func() *int32 { i := int32(1); return &i }(),
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"previewer-id": previewerId,
					},
				},
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{
						{
							Name:            "sidecar",
							Image:           sidecarImageName,
							ImagePullPolicy: corev1.PullIfNotPresent,
							Env: func() []corev1.EnvVar {
								ret := []corev1.EnvVar{}
								for k, v := range sidecarContainerEnv {
									ret = append(ret, corev1.EnvVar{
										Name:  k,
										Value: v,
									})
								}
								return ret
							}(),
							Ports: func() []corev1.ContainerPort {
								ret := []corev1.ContainerPort{}
								for k, v := range sidecarContainerPort {
									ret = append(ret, corev1.ContainerPort{
										Name:          k,
										ContainerPort: v,
									})
								}
								return ret
							}(),
							VolumeMounts: []corev1.VolumeMount{
								{
									Name:      "jsbundles",
									MountPath: "/data/jsBundles",
									ReadOnly:  false,
								},
							},
						},
						{
							Name:            "previewer",
							Image:           previewerImageName,
							ImagePullPolicy: corev1.PullIfNotPresent,
							Env: func() []corev1.EnvVar {
								ret := []corev1.EnvVar{}
								for k, v := range previewerContainerEnv {
									ret = append(ret, corev1.EnvVar{
										Name:  k,
										Value: v,
									})
								}
								return ret
							}(),
							Ports: func() []corev1.ContainerPort {
								ret := []corev1.ContainerPort{}
								for k, v := range previewerContainerPort {
									ret = append(ret, corev1.ContainerPort{
										Name:          k,
										ContainerPort: v,
									})
								}
								return ret
							}(),
							VolumeMounts: []corev1.VolumeMount{
								{
									Name:      "jsbundles",
									MountPath: "/data/jsBundles",
									ReadOnly:  false,
								},
							},
						},
					},
					Volumes: []corev1.Volume{
						{
							Name: "jsbundles",
							VolumeSource: corev1.VolumeSource{
								EmptyDir: &corev1.EmptyDirVolumeSource{},
							},
						},
					},
				},
			},
		},
	}
	_, e = appClient.Create(ctx, dep, metav1.CreateOptions{})
	return
}

func GetService(
	kubeClient *kubernetes.Clientset,
	ctx context.Context,
	previewerId,
	namespace string,
) (*corev1.Service, error) {
	serviceCli := kubeClient.CoreV1().Services(namespace)
	return serviceCli.Get(ctx, previewerId, metav1.GetOptions{})
}

func DeleteService(
	kubeClient *kubernetes.Clientset,
	ctx context.Context,
	previewerId,
	namespace string,
) (error) {
	serviceCli := kubeClient.CoreV1().Services(namespace)
	return serviceCli.Delete(ctx, previewerId, metav1.DeleteOptions{})
}

// CreateService
func CreateService(
	kubeClient *kubernetes.Clientset,
	ctx context.Context,
	previewerId,
	namespace string,
	servicePorts map[int32]int32,
) (e error) {
	serviceCli := kubeClient.CoreV1().Services(namespace)
	svc := &corev1.Service{
		TypeMeta: metav1.TypeMeta{
			Kind:       "Service",
			APIVersion: "v1",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      previewerId,
			Namespace: namespace,
		},
		Spec: corev1.ServiceSpec{
			Type: corev1.ServiceTypeClusterIP,
			Ports: func() []corev1.ServicePort {
				ret := []corev1.ServicePort{}
				for k, v := range servicePorts {
					ret = append(ret, corev1.ServicePort{
						Port:       k,
						TargetPort: intstr.FromInt(int(v)),
						Protocol:   corev1.ProtocolTCP,
						Name: fmt.Sprintf("port-%v", k),
					})
				}
				return ret
			}(),
			Selector: map[string]string{
				"previewer-id": previewerId,
			},
		},
	}
	_, e = serviceCli.Create(ctx, svc, metav1.CreateOptions{})
	return
}
